/* eslint-disable @typescript-eslint/no-explicit-any */
// TODO Remove this when V6
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import { graphql, useSubscription } from 'react-relay';
import { Link, Route, Routes, useParams, useLocation } from 'react-router-dom';
import React, { useMemo } from 'react';
import { GraphQLSubscriptionConfig } from 'relay-runtime';
import Box from '@mui/material/Box';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import StixCoreObjectContentRoot from '@components/common/stix_core_objects/StixCoreObjectContentRoot';
import Security from 'src/utils/Security';
import { KNOWLEDGE_KNUPDATE } from 'src/utils/hooks/useGranted';
import { QueryRenderer } from '../../../../relay/environment';
import ErrorNotFound from '../../../../components/ErrorNotFound';
import Loader from '../../../../components/Loader';
import MalwareAnalysis from './MalwareAnalysis';
import { RootMalwareAnalysisSubscription } from './__generated__/RootMalwareAnalysisSubscription.graphql';
import { RootMalwareAnalysisQuery$data } from './__generated__/RootMalwareAnalysisQuery.graphql';
import StixDomainObjectHeader from '../../common/stix_domain_objects/StixDomainObjectHeader';
import MalwareAnalysisPopover from './MalwareAnalysisPopover';
import EntityStixCoreRelationships from '../../common/stix_core_relationships/EntityStixCoreRelationships';
import FileManager from '../../common/files/FileManager';
import StixCoreObjectHistory from '../../common/stix_core_objects/StixCoreObjectHistory';
import StixCoreRelationship from '../../common/stix_core_relationships/StixCoreRelationship';
import { useFormatter } from '../../../../components/i18n';
import Breadcrumbs from '../../../../components/Breadcrumbs';
import { getMainRepresentative } from '../../../../utils/defaultRepresentatives';
import { getCurrentTab, getPaddingRight } from '../../../../utils/utils';
import MalwareAnalysisEdition from './MalwareAnalysisEdition';

const subscription = graphql`
  subscription RootMalwareAnalysisSubscription($id: ID!) {
    stixDomainObject(id: $id) {
      ... on MalwareAnalysis {
        ...MalwareAnalysis_malwareAnalysis
      }
      ...FileImportViewer_entity
      ...FileExportViewer_entity
      ...FileExternalReferencesViewer_entity
      ...WorkbenchFileViewer_entity
    }
  }
`;

const malwareAnalysisQuery = graphql`
  query RootMalwareAnalysisQuery($id: String!) {
    malwareAnalysis(id: $id) {
      id
      standard_id
      product
      result_name
      x_opencti_graph_data
      ...MalwareAnalysis_malwareAnalysis
      ...FileImportViewer_entity
      ...FileExportViewer_entity
      ...FileExternalReferencesViewer_entity
      ...WorkbenchFileViewer_entity
    }
    connectorsForImport {
      ...FileManager_connectorsImport
    }
    connectorsForExport {
      ...FileManager_connectorsExport
    }
  }
`;

const RootMalwareAnalysis = () => {
  const { malwareAnalysisId } = useParams() as { malwareAnalysisId: string };
  const subConfig = useMemo<
  GraphQLSubscriptionConfig<RootMalwareAnalysisSubscription>
  >(
    () => ({
      subscription,
      variables: { id: malwareAnalysisId },
    }),
    [malwareAnalysisId],
  );
  const location = useLocation();
  const { t_i18n } = useFormatter();
  useSubscription(subConfig);
  const link = `/dashboard/analyses/malware_analyses/${malwareAnalysisId}/knowledge`;
  return (
    <>
      <QueryRenderer
        query={malwareAnalysisQuery}
        variables={{ id: malwareAnalysisId }}
        render={({ props }: { props: RootMalwareAnalysisQuery$data }) => {
          if (props) {
            if (props.malwareAnalysis) {
              const { malwareAnalysis } = props;
              const paddingRight = getPaddingRight(location.pathname, malwareAnalysis.id, '/dashboard/analyses/malware_analyses', false);
              return (
                <div style={{ paddingRight }}>
                  <Breadcrumbs variant="object" elements={[
                    { label: t_i18n('Analyses') },
                    { label: t_i18n('Malware analyses'), link: '/dashboard/analyses/malware_analyses' },
                    { label: getMainRepresentative(malwareAnalysis), current: true },
                  ]}
                  />
                  <StixDomainObjectHeader
                    entityType={'Malware-Analysis'}
                    stixDomainObject={malwareAnalysis}
                    PopoverComponent={
                      <MalwareAnalysisPopover id={malwareAnalysisId} />
                    }
                    EditComponent={(
                      <Security needs={[KNOWLEDGE_KNUPDATE]}>
                        <MalwareAnalysisEdition malwareAnalysisId={malwareAnalysis.id} />
                      </Security>
                    )}
                    noAliases={true}
                  />
                  <Box
                    sx={{
                      borderBottom: 1,
                      borderColor: 'divider',
                      marginBottom: 3,
                    }}
                  >
                    <Tabs
                      value={getCurrentTab(location.pathname, malwareAnalysis.id, '/dashboard/analyses/malware_analyses')}
                    >
                      <Tab
                        component={Link}
                        to={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}`}
                        value={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}`}
                        label={t_i18n('Overview')}
                      />
                      <Tab
                        component={Link}
                        to={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/knowledge`}
                        value={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/knowledge`}
                        label={t_i18n('Knowledge')}
                      />
                      <Tab
                        component={Link}
                        to={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/content`}
                        value={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/content`}
                        label={t_i18n('Content')}
                      />
                      <Tab
                        component={Link}
                        to={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/files`}
                        value={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/files`}
                        label={t_i18n('Data')}
                      />
                      <Tab
                        component={Link}
                        to={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/history`}
                        value={`/dashboard/analyses/malware_analyses/${malwareAnalysis.id}/history`}
                        label={t_i18n('History')}
                      />
                    </Tabs>
                  </Box>
                  <Routes>
                    <Route
                      path="/"
                      element={
                        <MalwareAnalysis
                          data={malwareAnalysis}
                        />}
                    />
                    <Route
                      path="/knowledge"
                      element={
                        <EntityStixCoreRelationships
                          entityId={malwareAnalysisId}
                          relationshipTypes={[
                            'related-to',
                            'duplicate-of',
                            'derived-from',
                            'characterizes',
                            'analysis-of',
                            'static-analysis-of',
                            'dynamic-analysis-of',
                          ]}
                          entityLink={link}
                          defaultStartTime={malwareAnalysis.first_seen}
                          defaultStopTime={malwareAnalysis.last_seen}
                          allDirections={true}
                          paddingRightButtonAdd={0}
                        />}
                    />
                    <Route
                      path="/knowledge/relations/:relationId"
                      element={
                        <StixCoreRelationship
                          entityId={malwareAnalysisId}
                        />}
                    />
                    <Route
                      path="/content/*"
                      element={
                        <StixCoreObjectContentRoot
                          stixCoreObject={malwareAnalysis}
                        />
                      }
                    />
                    <Route
                      path="/files"
                      element={
                        <FileManager
                          id={malwareAnalysisId}
                          connectorsImport={props.connectorsForImport}
                          connectorsExport={props.connectorsForExport}
                          entity={malwareAnalysis}
                        />}
                    />
                    <Route
                      path="/history"
                      element={
                        <StixCoreObjectHistory
                          stixCoreObjectId={malwareAnalysisId}
                        />}
                    />
                  </Routes>
                </div>
              );
            }
            return <ErrorNotFound/>;
          }
          return <Loader />;
        }}
      />
    </>
  );
};
export default RootMalwareAnalysis;
